package cn.csc.module.shoppingCard.controller.admin.card;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.common.util.collection.CollectionUtils;
import cn.csc.framework.excel.core.util.ExcelUtils;
import cn.csc.framework.operatelog.core.annotations.OperateLog;
import cn.csc.module.shoppingCard.controller.admin.card.vo.*;
import cn.csc.module.shoppingCard.controller.admin.transaction.vo.CardTransactionGroupByCardIdsRespVO;
import cn.csc.module.shoppingCard.convert.card.CardConvert;
import cn.csc.module.shoppingCard.dal.dataobject.card.CardDO;
import cn.csc.module.shoppingCard.service.card.CardService;
import cn.csc.module.shoppingCard.service.transaction.CardTransactionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 购物卡主表")
@RestController
@RequestMapping("/shoppingCard/card")
@Validated
@Slf4j
public class CardController {

    @Resource
    private CardService cardService;

    @Resource
    private CardTransactionService cardTransactionService;

    @PostMapping("/create")
    @ApiOperation("创建购物卡")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:create')")
    public CommonResult<BigInteger> createCard(@Valid @RequestBody CardCreateReqVO createReqVO) {
        return success(cardService.createCard(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新购物卡")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:update')")
    public CommonResult<Boolean> updateCard(@Valid @RequestBody CardUpdateReqVO updateReqVO) {
        cardService.updateCard(updateReqVO);
        return success(true);
    }


    @DeleteMapping("/delete")
    @ApiOperation("删除购物卡")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = BigInteger.class)
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:delete')")
    public CommonResult<Boolean> deleteCard(@RequestParam("id") BigInteger id) {
        cardService.deleteCard(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得购物卡")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = BigInteger.class)
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:query')")
    public CommonResult<CardRespVO> getCard(@RequestParam("id") BigInteger id) {
        CardDO card = cardService.getCard(id);
        return success(CardConvert.INSTANCE.convert(card));
    }

    @GetMapping("/list")
    @ApiOperation("获得购物卡列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:query')")
    public CommonResult<List<CardRespVO>> getCardList(@RequestParam("ids") List<BigInteger> ids) {
        List<CardDO> list = cardService.getCardList(ids);
        List<CardRespVO> respVOS = CardConvert.INSTANCE.convertList(list);
        respVOS.forEach(c -> {
            if (LocalDateTime.now().isAfter(c.getExpireTime())){
                c.setExpired(true);
            }
        });
        return success(respVOS);
    }

    @GetMapping("/page")
    @ApiOperation("获得购物卡分页")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:query')")
    public CommonResult<PageResult<CardRespVO>> getCardPage(@Valid CardPageReqVO pageVO) {
        PageResult<CardDO> pageResult = cardService.getCardPage(pageVO);
        PageResult<CardRespVO> convertPage = CardConvert.INSTANCE.convertPage(pageResult);
        if (CollectionUtils.isAnyEmpty(convertPage.getList())){
            return success(convertPage);
        }
        // 购物卡使用的订单数
        List<BigInteger> cardIds = pageResult.getList().stream().map(CardDO::getId).collect(Collectors.toList());
        List<CardTransactionGroupByCardIdsRespVO> list = cardTransactionService.groupByCardIds(cardIds, 2, 1);
        Map<BigInteger, Integer> map = CollectionUtils.convertMap(list, CardTransactionGroupByCardIdsRespVO::getCardId, CardTransactionGroupByCardIdsRespVO::getCount);
        log.info("getCardPage map : {}", map);
        convertPage.getList().forEach(c -> {
            if (LocalDateTime.now().isAfter(c.getExpireTime())){
                c.setExpired(true);
            }
            if (map != null){
                c.setOrderCount(map.getOrDefault(c.getId(),0));
            }
        });
        return success(convertPage);
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出购物卡 Excel")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card:export')")
    @OperateLog(type = EXPORT)
    public void exportCardExcel(@Valid CardExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<CardDO> list = cardService.getCardList(exportReqVO);
        // 导出 Excel
        List<CardExcelVO> datas = CardConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "购物卡.xls", "数据", CardExcelVO.class, datas);
    }

}
